const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
let todoArr = require('../model/todoModel').todo;
let router = express.Router();
let jsonParser = bodyParser.json();
let urlencodedParser = bodyParser.urlencoded({ extended: false });

mongoose.connect(
    'mongodb+srv://wayn:he201011@cluster0-gx84p.mongodb.net/db_todo',
    { useNewUrlParser: true }
);
//mongoose.connect('mongodb://hfpp2012:hfpp2012@ds151068.mlab.com:51068/todos');
//测试mongo的连接
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    // we're connected!
    console.log("we're connected!");
});
    
let todoSchema = new mongoose.Schema({
    item: String
});
let Todo = mongoose.model('Todo', todoSchema);
router.use(
    '/todo',
    function(req, res, next) {
        console.log('Request URL:', req.originalUrl);
        next();
    },
    function(req, res, next) {
        console.log('Request Type:', req.method);
        next();
    }
);

router.get('/', function(req, res) {
    Todo.find({}, function(err, data) {
        if (err) return console.error(err);
        res.render('todo', { todos: data });
    });
});

router.post('/todo', urlencodedParser, function(req, res) {
    const kitty = new Todo({ item: req.body.item });
    kitty.save(function(err, data) {
        if (err) {
            console.log(err);
            return;
        }
        res.json(data);
    });
});

router.post('/get', urlencodedParser, function(req, res) {
    console.log(req.body.item);
    Todo.find({ item: req.body.item }, function(err, data) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(data);
        res.json(data);
    });
});

router.delete('/todo/:item', urlencodedParser, function(req, res) {
    /* todoArr = todoArr.filter(function(todo) {
        return todo.item.replace(/ /g, '-') !== req.params.item; //如果 req.params.item中带有空格，express回自动将空格转化为 '-'
    }); */
    Todo.remove({ item: req.params.item.replace(/ /g, '-') }, function(
        err,
        data
    ) {
        if (err) {
            console.log(err);
            return;
        }
        res.json(todoArr);
    });
});

module.exports = {
    router: router
};
